package com.ngkj.zmfptes.config;

import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 初始化索引
 * @author ChenHN
 * @since 2021/11/8 creation
 **/
@Slf4j
@Component
public class EsIndexInit {

    private static List<String> indexList = Arrays.asList("ng_rental_info","chenhaonan");

    @Resource
    private RestHighLevelClient client;

    @PostConstruct
    public void init(){
        indexList.forEach(index->{
            try {
                //判断索引存在
                GetIndexRequest request = new GetIndexRequest(index);
                boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
                if (!exists){
                    //创建索引
                    CreateIndexRequest request1 = new CreateIndexRequest(index);
                    CreateIndexResponse createIndexResponse = client.indices().create(request1, RequestOptions.DEFAULT);
                    log.info("初始化索引 {} 成功 。",index);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        });
    }
}
